import * as React from 'react';
import * as Reflux from 'reflux';
import {
    IN
}
from './in-union';
import {
    SUB
}
from './sub';
var $ = require("jquery");


var VALIDE = require("./valide.js").VALIDE;

var Tr_row = React.createClass({
    getInitialState: function() {
        return {
            isShowDialog: false,
            data: {},

        }
    },
    componentWillMount: function() {
        this.setState(this.props.rows)
    },
    setFormValue: function(item) {
        var data = this.state.data;
        data[item.name] = item.value;
        if (typeof(item.name) == "string") {
            data[item.name] = item.value;
        } else if (item.name instanceof Array) {
            for (var i = 0; i < item.name.length; i++) {
                data[item.name[i]] = item.value[item.name[i]];
            }
        };
        this.setState({
            "data": data
        })

        this.props.setFormValue(this.props.index, item);
    },
    changState: function(value) {
        return this.setState(value);
    },
    componentDidMount: function() {
        console.log("***************************************a***********************************")
        if (this.props.defaultValue != "") {
            //this.handleBlur();
        }
    },
    componentDidUpdate: function() {
        console.log("***************************************componentDidUpdate***********************************")
    },
    getState: function(name) {
        return this.state[name];
    },
    handleBlur: function() {
        var $this = this;
        var key, state = $this.state,
            temp, newState = {},
            isVa = true;
        for (key in state) {
            temp = state[key];
            //console.log("难道  您 不验证 一下吗？");
            if (temp.errorMessage == false && temp.defaultValue != "") {
                //temp.errorMessage = temp.vaMethod?temp.vaMethod():true;
                if (temp.vaMethod) {
                    temp.errorMessage = temp.vaMethod()
                } else {
                    temp.errorMessage = true
                }
            }
            if (temp.title && temp.errorMessage != true && temp.isStar) {
                temp.errorMessage = temp.errorMessage == false ? "不能为空" : temp.errorMessage;
                //console.log("error:" + temp.errorMessage);
                newState[key] = temp;
                isVa = false;
            }
        }
        $this.setState(newState);
        // console.info(" sub create  this.setState:" + JSON.stringify(newState));
        $this.props.handleBlur($this.props.index, isVa);

    },
    removeItem: function() {
        this.props.removeSelf(this.props.index)
    },
    /*<td key={temp.name}><IN param={this.state[temp.name]} changState={this.changState} getState={this.getState} setFormValue={this.setFormValue}/></td>*/
    render: function() {
        var rows = this.props.rows,
            $rows = [],
            temp;
        for (var key in rows) {
            temp = rows[key];
            $rows.push(
                <td key={temp.name}><IN vaDoneMethod={this.handleBlur} param={this.state[temp.name]} changState={this.changState} getState={this.getState} setFormValue={this.setFormValue}/></td>
            )
        }
        return (

            <tr>
                {$rows}                                                
                <td><button onClick={this.removeItem} className="btn btn-icon icon-edi">删除</button></td>
            </tr>
        )
    }
});
/*onMouseLeave={this.handleBlur}*/


//this.props.param.title this.props.param.isStar
var Table_in = React.createClass({
        getDefaultProps: function() {
            return {
                isDel: true
            }
        },
        getInitialState: function() {
            return {
                data: {},
                trNum: 0, //row key  不断自增 不减
                trArray: [{
                    "key": 0
                }], // rows 自增自减
                trMap: {
                    0: false
                }
            }
        },
        clone: function(obj) {
            var temp = $.extend(true, {}, obj);
            return temp;
        },
        componentWillMount: function() {
            this.initValue(this.props.param.defaultValue, this.state);

        },
        initValue: function(defaultValue, state) {
            var trArray = [],
                startNum = (state.trNum + 1),
                trMap = {},
                rows = {},
                tempMap = {},
                tempRow = {},
                tempKey = 0,
                trNum;

            if (defaultValue && defaultValue != "") {
                trNum = startNum + defaultValue.length;
                for (var i = 0; i < defaultValue.length; i++) {
                    //过滤掉空数据
                    if (defaultValue[i] != null) {
                        tempKey = startNum + i;
                        //rows = Object.create(this.props.rows);
                        rows = $.extend(true, {}, this.props.rows);
                        trArray.push({
                            "key": tempKey
                        });
                        tempMap = defaultValue[i]; //{"supplierID":"2","unitPrice":"333"}
                        for (var key in rows) {
                            rows[key]["defaultRowData"] = tempMap;
                            rows[key]["defaultValue"] = tempMap[key]; //
                            rows[key]["defaultShowName"] = (rows[key]["showName"] ? (tempMap[rows[key]["showName"]]) : "");
                            //rows[key]["searchParam"] = rows[key]["setProp"]?rows[key]["setProp"](tempMap[key]):"";
                            if (rows[key]["setProp"]) {
                                rows[key] = rows[key]["setProp"](rows[key], tempMap);
                            }
                        }
                        //trMap[i] = Object.create(rows);
                        trMap[tempKey] = $.extend(true, {}, rows);
                        rows = {};
                    }

                }
                console.info("union say ----------------------" + JSON.stringify(trMap));
                //console.info(trMap)
                this.setState({
                    "trNum": trNum,
                    "trArray": trArray,
                    "trMap": trMap
                })
            } else {
                trMap[startNum] = false;
                this.setState({
                    "trNum": startNum,
                    "trArray": [{
                        "key": startNum
                    }],
                    "trMap": trMap
                })

            }
        },
        onStatusChange: function(rows) {

        },
        setFormValue: function(i, item) {
            var trArray = this.state.trArray,
                temp;

            temp = trArray[i];
            temp[item.name] = item.value;
            trArray[i] = temp;

            // console.info("-Table_in  say -------------"+JSON.stringify(item))
            this.setState({
                "trArray": trArray,
            });
            this.setValueToAction(trArray);
        },
        setValueToAction: function(value) {
            var name = this.props.param.name;
            var data = this.props.getState("data");
            data[name] = value;
            if (typeof(name) == "string") {
                data[name] = value;
            } else if (name instanceof Array) {
                for (var i = 0; i < name.length; i++) {
                    data[name[i]] = value[name[i]];
                    //console.log("设置表格值：" + name[i] + "   " + value[i])
                }
            }
            this.props.changState({
                "data": data
            })
            console.log("表单数据:" + JSON.stringify(data));
        },
        //设置每一行的  错误
        handleBlur: function(index, isVa) {
            var trArray = this.state.trArray,
                temp;
            temp = trArray[index];
            temp.isVa = isVa;
            this.setState({
                "trArray": trArray
            })
        },
        moveLeave: function() {
            console.info("====================================、、、、、、、、、、、=")
            var trArray = this.state.trArray,
                temp, isVa = false;
            for (var i = 0; i < trArray.length; i++) {
                if (trArray[i].isVa) {
                    isVa = true;
                } else if (trArray[i].isVa == false || (this.props.param.isStar && !trArray[i].isVa)) {
                    isVa = false;
                    break;
                } else {
                    isVa = true;
                }
            }

            var param = this.props.param,
                vaMessage = "",
                temp = {};
            if (isVa) {
                param.errorMessage = true;
            } else {
                param.errorMessage = "不能为空!";
            }
            temp[this.props.param.name] = param;
            this.props.changState(temp);
        },
        shouldComponentUpdate: function(nextProps, nextState) {
            //console.info("=====================================")
            if (nextProps.isLoadNew) {
                console.log(nextProps)
                var newState = nextProps.param;
                newState.isLoadNew = false;
                var temp = {};
                temp[newState.name] = newState
                this.initValue(nextProps.param.defaultValue, nextState);
                //暂行办法 
                setTimeout(function() {
                    this.props.changState(temp);
                }.bind(this), 200)

            }
            return true
        },

        removeAll: function(nextState) {
            var index = Number(nextState.trNum + 100);
            var trMap = {};
            trMap[index] = false;
            this.setState({
                "trNum": index, //row key  不断自增 不减
                "trArray": [{
                    "key": index
                }], // rows 自增自减
                "trMap": trMap
            })
        },
        addItem: function() {
            ////console.log("table in sya  addItem");
            var trArray = this.state.trArray,
                trNum = this.state.trNum,
                trMap = this.state.trMap;
            trNum += 1;
            trArray.push({
                "key": trNum
            });
            this.setState({
                trArray: trArray,
                trNum: trNum
            })

        },
        removeItem: function(i) {
            //console.log("table in sya  removeItem");
            var trArray = this.state.trArray,
                trMap = this.state.trMap;

            if (trArray.length == 1) {
                this.addItem();
                trArray.splice(i, 1);
                delete trMap[i];
                this.setState({
                    trArray: trArray
                })
            } else {
                trArray.splice(i, 1);
                delete trMap[i];
                this.setState({
                    trArray: trArray
                })
            }
        },
        removeItems: function(arr) {
            console.log(arr);
            if (arr.length == 0) {
                return;
            }

            var trArray = this.state.trArray,
                trMap = this.state.trMap,
                trNum = this.state.trNum;

            // if (arr.length == trArray.length) {
            //     this.removeAll(this.state);
            //     this.addItem();
            // }

            if (trArray.length == 1) {
                this.addItem();
                trArray.splice(arr[0], 1);
                delete trMap[arr[0]];
                this.setState({
                    trArray: trArray
                })
                return;
            }

            for (let i = 0; i < arr.length; i++) {
                trArray[arr[i]] = null;
                delete trMap[arr[i]];
            }

            var tempTrArray = [];

            for (let i = 0; i < trArray.length; i++) {
                if (trArray[i]) {
                    tempTrArray.push(trArray[i]);
                }
            }

            if (arr.length == trArray.length) {
                tempTrArray.push({
                    "key": trNum
                });
                trNum += 1;
            }

            this.setState({
                trArray: tempTrArray,
                trNum: trNum
            });
        },
        render: function() {
            var isShow = "form-label " + (this.props.param.isShow == false ? "hide" : "");

            var $tr = [],
                trArray = this.state.trArray;
            /*var tr = isClear?tt:(tempMap?tempMap:tt);*/
            var isClear = this.props.param.defaultValue == "" ? true : false;
            for (var i = 0; i < trArray.length; i++) {
                var tt = this.clone(this.props.rows);
                var tempMap = this.state.trMap[trArray[i]["key"]];
                var tr = (tempMap ? tempMap : tt);
                $tr.push(<Tr_row tempMap={tempMap} tt={tt} rows={tr} index={i} key={trArray[i]["key"]} a={trArray[i]["key"]} setFormValue={this.setFormValue} removeSelf={this.removeItem} handleBlur={this.handleBlur}/>)
            }
            var rows = this.props.rows,
                $rows = [],
                temp;
            for (var key in rows) {
                temp = rows[key];
                $rows.push(
                    <td key={temp.name}>{temp.title}</td>
                )
            }
            return (
                <div className="from-area" >
                    <label className={isShow}>
                        {this.props.param.title}
                        {(() => {
                            if (this.props.param.isStar == true) {
                                return (
                                    <i className="i-red">*</i>
                                )
                            }
                        })()}
                        ：
                    </label>
                    <div className="form-table">
                             <table onMouseLeave={this.moveLeave}> 
                                <thead>
                                    <tr>{$rows}<td>操作</td></tr>
                                </thead>
                                <tbody>
                                          {$tr}                                 
                                </tbody>
                            </table>
                            <VALIDE errorMessage={this.props.param.errorMessage} name={this.props.name}/>
                            <div className="form-row row-content-right">
                                <button onClick={this.addItem} className="btn btn-add">添加</button>
                            </div>

                    </div>
                    
            </div>
            )
        }
    })
    // / <Tr_row setFormValue={this.setFormValue}/>   <Tr_row setFormValue={this.setFormValue}/> 



/* for(var i=0;i<defaultValue.length;i++){
                rows = this.clone(this.props.rows);
                //rows = $.extend({},this.props.rows)
                trArray.push({"key":i});
                tempMap = defaultValue[i];  //{"supplierID":"2","unitPrice":"333"}
                for(var key in tempMap){
                    rows[key]["defaultValue"] = tempMap[key];//
                   // rows[key]["defaultShowName"] = (rows[key]["showName"]?(tempMap[rows[key]["showName"]]):"");
                }
                          
                trMap[i] = this.clone(rows);
               // trMap[i] = this.clone(rows);
                rows = {};
            }*/



module.exports = Table_in;